package cn.com.controller.operationController;

import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.com.Enum.OrderStatus;
import cn.com.Enum.UserAuth;
import cn.com.annotation.Auth;
import cn.com.constant.Code;
import cn.com.db.model.Address;
import cn.com.db.model.DiyOrder;
import cn.com.db.model.Order;
import cn.com.db.model.Store;
import cn.com.db.model.User;
import cn.com.db.model.WxDiyPayResult;
import cn.com.db.model.WxDiyRefundResult;
import cn.com.db.model.WxPayResult;
import cn.com.db.model.WxRefundResult;
import cn.com.db.service.AddressService;
import cn.com.db.service.DiyOrderService;
import cn.com.db.service.StoreService;
import cn.com.db.service.UserService;
import cn.com.db.service.WxDiyPayResultService;
import cn.com.db.service.WxDiyRefundResultService;
import cn.com.util.DataResult;
import cn.com.util.JsonUtil;
import cn.com.util.TimeUtil;
import cn.com.util.UidUtil;
import cn.com.wxUtil.SendTemplateMessageUtil;
import cn.com.wxUtil.XMLUtil;
import cn.com.wxUtil.wxConstant;
import cn.com.wxUtil.refundUtil.RefundConstant;
import cn.com.wxUtil.refundUtil.WeiXinAtcion;
import cn.com.wxUtil.template.TemplateData;
import cn.com.wxUtil.template.WechatTemplate;

@Auth(UserAuth.SELLER)
@RestController
@RequestMapping("/operation/diyorder/")
public class DiyOrderOperationController {

	@Autowired
	DiyOrderService diyOrderService;
	@Autowired
	UserService userService;
	@Autowired
	StoreService storeService;
	@Autowired
	WxDiyPayResultService wxDiyPayResultService;
	@Autowired
	WxDiyRefundResultService wxDiyRefundResultService;
	@Autowired
	AddressService addressService;

	@RequestMapping(value = "/getStoreDiyOrder", method = RequestMethod.POST)
	public String getStoreDiyOrder(@RequestParam("storeId") String storeId,
			@RequestParam(value = "status", required = false) Integer status, @RequestParam("page") Integer page,
			@RequestParam("count") Integer count) {
		DataResult dataResult = new DataResult(page, count);
		DiyOrder order = new DiyOrder();
		order.setStore(storeId);
		order.setStatus(status);
		dataResult.setTotal(diyOrderService.countDiyOrder(order));
		dataResult.setData(diyOrderService.getDiyOrder(order, page, count));
		dataResult.setCode(Code.SUCCESS);
		dataResult.setMessage("返回成功");
		return JsonUtil.toJsonString(dataResult);
	}

	@RequestMapping(value = "/doDiyOrder", method = RequestMethod.POST)
	public String doDiyOrder(@RequestParam("orderId") String orderId) throws Exception {
		DataResult dataResult = new DataResult();
		DiyOrder order = diyOrderService.getDiyOrderById(orderId);
		if (order == null) {
			dataResult.setCode(Code.NOT_FOUND);
			dataResult.setMessage("订单不存在");
			return JsonUtil.toJsonString(dataResult);
		}
		if (!order.getStatus().equals(OrderStatus.WAIT_ORDERS.getStatus())) {
			dataResult.setCode(Code.FORBIDDEN);
			dataResult.setMessage("订单状态错误");
			return JsonUtil.toJsonString(dataResult);
		}
		diyOrderService.updateDiyOrderStatus(orderId, OrderStatus.WAIT_TRANS.getStatus());

		dataResult.setData(diyOrderService.getDiyOrderById(orderId));
		dataResult.setCode(Code.SUCCESS);
		dataResult.setMessage("接单成功");
		return JsonUtil.toJsonString(dataResult);
	}

	@RequestMapping(value = "/refuseDiyOrder", method = RequestMethod.POST)
	public String refuseDiyOrder(@RequestParam("orderId") String orderId) throws Exception {
		DataResult dataResult = new DataResult();
		DiyOrder order = diyOrderService.getDiyOrderById(orderId);
		if (order == null) {
			dataResult.setCode(Code.NOT_FOUND);
			dataResult.setMessage("订单不存在");
			return JsonUtil.toJsonString(dataResult);
		}
		if (!order.getStatus().equals(OrderStatus.WAIT_ORDERS.getStatus())) {
			dataResult.setCode(Code.FORBIDDEN);
			dataResult.setMessage("订单状态错误");
			return JsonUtil.toJsonString(dataResult);
		}

		/******************* 发送模板消息 ************************/
		// 拒单提醒
		WechatTemplate w = new WechatTemplate();
		String userId = order.getUser();
		User user = userService.getUserAuthingId(userId);
		String openid = user.getOpenId();
		w.setTouser(openid);
		String page = "/pages/my";
		w.setPage(page);
		String prepayId = wxDiyPayResultService.getPrepayIdByOrderId(orderId);
		w.setForm_id(prepayId);
		w.setTemplate_id(wxConstant.TEMPLATE_ID_REFUSEORDER);
		LinkedHashMap<String, TemplateData> map = new LinkedHashMap<>();
		TemplateData t1 = new TemplateData();
		t1.setValue(order.getPrice().toString());
		t1.setColor("#000000");
		map.put("keyword1", t1);
		TemplateData t2 = new TemplateData();
		t2.setValue(order.getId());
		t2.setColor("#000000");
		map.put("keyword2", t2);
		TemplateData t3 = new TemplateData();
		DiyOrder order1 = diyOrderService.getDiyOrderById(orderId);
		String time = order1.getUpdated_at().toString();
		time = time.substring(0, time.indexOf("."));
		t3.setValue(time);
		t3.setColor("#000000");
		map.put("keyword3", t3);
		w.setData(map);
		String jsonTemplate = JSONObject.toJSON(w).toString();
		System.out.println(jsonTemplate);
		// String message = "";
		try {
			SendTemplateMessageUtil.send(jsonTemplate);
		} catch (Exception e) {
			// message += ",但距离支付完成超过七天将不发送";
		}
		/*******************************************/

		/************** 退款 ********************/
		WxDiyPayResult payResult = wxDiyPayResultService.getPayResultByOrderId(orderId);
		if (payResult == null) {
			dataResult.setCode(Code.FORBIDDEN);
			dataResult.setMessage("该订单未支付成功或不存在,请重新支付");
			return JsonUtil.toJsonString(dataResult);
		}
		String out_trade_no = payResult.getId(); // 退款订单
		String xmlWxInfo = payResult.getWx_meta_info();
		Map xmlMap = XMLUtil.doXMLParse(xmlWxInfo);
		String total_fee = (String) xmlMap.get("cash_fee");
		BigDecimal all_total_fee = new BigDecimal(total_fee); // 订单金额
		BigDecimal refund_fee = order.getTotalPrice().movePointRight(2); // 退款金额
		String appid = wxConstant.APPID; // 微信小程序--》“开发者ID”
		String mch_id = wxConstant.MCH_ID; // 商户号，将该值赋值给partner
		String key = wxConstant.PAY_KEY; // 微信支付商户平台登录）--》“API安全”--》“API密钥”--“设置密钥”（设置之后的那个值就是partnerkey，32位）

		Map<String, String> refundmap = WeiXinAtcion.wechatRefund(mch_id, appid, key, out_trade_no, all_total_fee,
				refund_fee);

		String resultJson = JSON.toJSONString(refundmap);
		// 退款之后业务逻辑 : 修改订单状态,新建数据库表
		WxDiyRefundResult wxRefundResult = new WxDiyRefundResult();
		if (refundmap.get("return_code").equals("SUCCESS")) {
			if (refundmap.get("result_code").equals("FAIL")) {
				// 失败
				// dataResult.setData(refundmap.get("err_code_des"));
				wxRefundResult.setId(UidUtil.createUUID());
				wxRefundResult.setOrder(orderId);
				wxRefundResult.setSeller(order.getSeller());
				wxRefundResult.setUser(order.getUser());
				wxRefundResult.setStore(order.getStore());
				wxRefundResult.setWx_meta_info(resultJson); // 存的json
				wxRefundResult.setType(RefundConstant.DIYTYPE);
				wxRefundResult.setResult(false);
				wxRefundResult.setCreated_at(TimeUtil.getNowTimestamp());
				wxRefundResult.setUpdated_at(TimeUtil.getNowTimestamp());
				wxDiyRefundResultService.createDiyRefundResult(wxRefundResult);
				dataResult.setCode(Code.REFUND_FAIL);
				dataResult.setMessage("「取消订单失败，原因：退款失败，请稍候再试」");
				return JsonUtil.toJsonString(dataResult);
			} else {
				wxRefundResult.setId(UidUtil.createUUID());
				wxRefundResult.setOrder(orderId);
				wxRefundResult.setSeller(order.getSeller());
				wxRefundResult.setUser(order.getUser());
				wxRefundResult.setStore(order.getStore());
				wxRefundResult.setWx_meta_info(resultJson); // 存的json
				wxRefundResult.setType(RefundConstant.DIYTYPE);
				wxRefundResult.setResult(true);
				wxRefundResult.setCreated_at(TimeUtil.getNowTimestamp());
				wxRefundResult.setUpdated_at(TimeUtil.getNowTimestamp());
				wxDiyRefundResultService.createDiyRefundResult(wxRefundResult);
			}
		} else {
			// 失败
			// dataResult.setData(refundmap.get("return_ms"));
			wxRefundResult.setId(UidUtil.createUUID());
			wxRefundResult.setOrder(orderId);
			wxRefundResult.setSeller(order.getSeller());
			wxRefundResult.setUser(order.getUser());
			wxRefundResult.setStore(order.getStore());
			wxRefundResult.setWx_meta_info(resultJson); // 存的json
			wxRefundResult.setType(RefundConstant.DIYTYPE);
			wxRefundResult.setResult(false);
			wxRefundResult.setCreated_at(TimeUtil.getNowTimestamp());
			wxRefundResult.setUpdated_at(TimeUtil.getNowTimestamp());
			wxDiyRefundResultService.createDiyRefundResult(wxRefundResult);
			dataResult.setCode(Code.REFUND_FAIL);
			dataResult.setMessage("「取消订单失败，原因：退款失败，请稍候再试」");
			return JsonUtil.toJsonString(dataResult);
		}
		/**********************************/
		diyOrderService.updateDiyOrderStatus(orderId, OrderStatus.REJECTION.getStatus());

		dataResult.setData(diyOrderService.getDiyOrderById(orderId));
		dataResult.setCode(Code.SUCCESS);
		dataResult.setMessage("拒单成功");
		return JsonUtil.toJsonString(dataResult);
	}

	@RequestMapping(value = "/transDiyOrder", method = RequestMethod.POST)
	public String transDiyOrder(@RequestParam("orderId") String orderId,
			@RequestParam(value = "form_id", required = false) String form_id) {
		DataResult dataResult = new DataResult();
		DiyOrder order = diyOrderService.getDiyOrderById(orderId);
		if (order == null) {
			dataResult.setCode(Code.NOT_FOUND);
			dataResult.setMessage("订单不存在");
			return JsonUtil.toJsonString(dataResult);
		}
		if (!order.getStatus().equals(OrderStatus.WAIT_TRANS.getStatus())) {
			dataResult.setCode(Code.FORBIDDEN);
			dataResult.setMessage("订单状态错误");
			return JsonUtil.toJsonString(dataResult);
		}
		diyOrderService.updateDiyOrderStatus(orderId, OrderStatus.TRANING.getStatus());
		/**************** 发送模板消息 *********************/
		// 发货提醒
		WechatTemplate w = new WechatTemplate();
		String userId = order.getUser();
		User user = userService.getUserAuthingId(userId);
		String openid = user.getOpenId();
		w.setTouser(openid);
		String page = "/pages/my";
		w.setPage(page);
		String prepayId = wxDiyPayResultService.getPrepayIdByOrderId(orderId);
		w.setForm_id(prepayId);
		w.setTemplate_id(wxConstant.TEMPLATE_ID_DELIVERGOODS);
		LinkedHashMap<String, TemplateData> map = new LinkedHashMap<>();
		TemplateData t1 = new TemplateData();
		String time = order.getUpdated_at().toString();
		time = time.substring(0, time.indexOf("."));
		t1.setValue(time);
		t1.setColor("#000000");
		map.put("keyword1", t1);
		TemplateData t2 = new TemplateData();
		WxDiyPayResult payResult = wxDiyPayResultService.getPayResultByOrderId(orderId);
		String buyTime = payResult.getUpdated_at().toString();
		buyTime = buyTime.substring(0, buyTime.indexOf("."));
		t2.setValue(buyTime);
		t2.setColor("#000000");
		map.put("keyword2", t2);
		TemplateData t3 = new TemplateData();
		t3.setValue(order.getId());
		t3.setColor("#000000");
		map.put("keyword3", t3);
		TemplateData t4 = new TemplateData();
		String addressString = order.getProvince() + order.getCity() + order.getDistrict() + order.getDetail();
		t4.setValue(addressString);
		t4.setColor("#000000");
		map.put("keyword4", t4);
		TemplateData t5 = new TemplateData();
		String storeId = order.getStore();
		Store store = storeService.getStoreById(storeId);
		t5.setValue(store.getName());
		t5.setColor("#000000");
		map.put("keyword5", t5);
		TemplateData t6 = new TemplateData();
		Address address = addressService.getUserDefAddress(userId);
		t6.setValue(address.getName());
		t6.setColor("#000000");
		map.put("keyword6", t6);
		TemplateData t7 = new TemplateData();
		t7.setValue(address.getPhone());
		t7.setColor("#000000");
		map.put("keyword7", t7);
		TemplateData t8 = new TemplateData();
		t8.setValue(order.getTotalPrice().toString() + "元");
		t8.setColor("#000000");
		map.put("keyword8", t8);
		TemplateData t9 = new TemplateData();
		t9.setValue(store.getPhone());
		t9.setColor("#000000");
		map.put("keyword9", t9);
		w.setData(map);
		String jsonTemplate = JSONObject.toJSON(w).toString();
		System.out.println(jsonTemplate);
		try {
			SendTemplateMessageUtil.send(jsonTemplate);
		} catch (Exception e) { // 可能超过七天prepay_id失效,就不发模板消息了
		}
		/************************************/

		dataResult.setData(diyOrderService.getDiyOrderById(orderId));
		dataResult.setCode(Code.SUCCESS);
		dataResult.setMessage("订单开始配送");
		return JsonUtil.toJsonString(dataResult);
	}
}
